package com.lk.service.impl;

import com.lk.mapper.UserMapper;
import com.lk.pojo.User;
import com.lk.service.UserService;
import com.lk.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class UserServiceImpl implements UserService {

    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    @Override
    public User login(String username, String password) {
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.select(username, password);

        sqlSession.close();
        return user;
    }

    @Override
    public boolean register(User user) {
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //判断用户名是否存在
        User u = mapper.selectByUsername(user.getUsername());

        if(u==null){
            mapper.add(user);
            sqlSession.commit();
        }

        sqlSession.close();

        return u==null;
    }

    @Override
    public User selectByUsername(String username) {
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.selectByUsername(username);

        sqlSession.close();
        return user;
    }
}
